package com.example.myapplication.blue.connect;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class AcceptThread extends Thread{
    private static final String NAME = "BlueToothClass";
    ///唯一ID
    private static final UUID MY_UUID = UUID.fromString(Constant.CONNECTTION_UUID);

    ///服务器插座
    private final BluetoothServerSocket mmServerSocket;
    ///蓝牙适配器
    private final BluetoothAdapter mBluetoothAdapter;
    ///服务器线程
    private final Handler mHandler;
    ///服务器连接线程
    private ConnectedThread mConnectedThread;


    ///线程构造函数
    @SuppressLint("MissingPermission")
    public AcceptThread(BluetoothAdapter adapter, Handler handler) {
        // 使用一个临时对象，该对象稍后被分配给mmServerSocket，因为mmServerSocket是最终的
        mBluetoothAdapter = adapter;
        mHandler = handler;
        ///中间插座
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID是应用程序的UUID，客户端代码使用相同的UUID
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) {

        }
        mmServerSocket = tmp;
    }


    ///线程执行
    public void run() {
        BluetoothSocket socket = null;
        //持续监听
        while (true){
            try{
                //线程发送数据：开始监听
                mHandler.sendEmptyMessage(Constant.MSG_START_LISTENING);
                //嵌套字接受数据
                socket = mmServerSocket.accept();
            }catch (IOException e){
                //异常就发送：出错
                mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_ERROR,e));
                break;
            }
        }
        //如果一个连接被接受
        if(socket != null){
            manageConnectedSocket(socket);
            try{
                mmServerSocket.close();
                mHandler.sendEmptyMessage(Constant.MSG_FINISH_LISTENING);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    //只支持同时处理一个连接
    private  void manageConnectedSocket(BluetoothSocket socket){
        if( mConnectedThread != null) {
            mConnectedThread.cancel();
        }
        //线程发送数据：有客户端连接
        mHandler.sendEmptyMessage(Constant.MSG_GOT_A_CLINET);
        //将当前线程赋值给连接线程
        mConnectedThread = new ConnectedThread(socket, mHandler);
        //线程开始
        mConnectedThread.start();
    }

    ///取消
    public void cancel(){
        try {
            ///关闭Socket
            mmServerSocket.close();
            ///线程发送消息:完成监听
            mHandler.sendEmptyMessage(Constant.MSG_FINISH_LISTENING);
        } catch (IOException e) {

        }
    }

    ///发送数据
    public void sendData(byte[] data){
        if( mConnectedThread!=null){
            mConnectedThread.write(data);
        }
    }

}
